// pages/group-purchase-commodity/commodity.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showsxselect: false,
    goodsID:"",
    shopdetails:'',
    juanshow:false,
    tuanshow:false,
    day:'',
    shi:'',
    fen:'',
    miao:'',
    scstate:'',
    pgid:'',
    coupon:'',
    beginnyr:'',
    endnyr:'',
    id:''
  },

  addobjselfnum: function () {

    var tonum = this.data.obj.selfnum
    tonum+=1

    if (this.data.obj.stylelength == 0) {
      var max = this.data.shopdetails[0].IQuantity
    }else{
      var max = this.data.obj.morenselect.IQuantity
    }

    if (tonum > max){
      wx.showToast({
        title: '已到最大库存',
        icon: 'none',
        duration: 2000
      })
    }else{
      var str = "obj.selfnum"
      this.setData({
        [str]: tonum
      })
    }
    
  },

  minusobjselfnum: function () {
    if (this.data.obj.selfnum != 0) {
      var str = "obj.selfnum"
      this.setData({
        [str]: this.data.obj.selfnum - 1
      })
    } else {
      return
    }

  },

  copyobj: function (a) {

    var c = {};

    c = JSON.parse(JSON.stringify(a));

    return c;

  },
  // 添加购物车
  clickadd: function (e) {

    var info = this.data.shopdetails[0]
    // console.log(info.IsSku)

    // console.log("11111111111")
    //有属性
    if (info.PT_SKUNV.length!=0) {
      if (info.PT_SKUNV.length == 2) {
        // 有附加属性选择
        var obj = {}
        obj.isdandu = e.currentTarget.dataset.isdandu == 1 ? true : false
        obj.stylelength = 2

        var PT_SKUNV = info.PT_SKUNV
        var PT_SKUIQuantity = info.PT_SKUIQuantity
        var canuselist = []
        for (var x in PT_SKUIQuantity) {
          canuselist.push(PT_SKUIQuantity[x].ANVS)
        }
        // obj.push(PT_SKUNV[0].AVNameStr)
        for (var x in PT_SKUNV) {
          if (x == 0) {
            obj.yiji = PT_SKUNV[x].AVNameStr

            obj.yijiANName = PT_SKUNV[x].ANName

            obj.selfnum = 0
          } else if (x == 1) {

            for (var y in obj.yiji) {
              var newlist = this.copyobj(PT_SKUNV[x].AVNameStr)
              for (var m in newlist) {
                newlist[m].zi = obj.yiji[y].AVID + '_' + newlist[m].AVID
                // console.log(newlist[m].zi)
                if (canuselist.indexOf(newlist[m].zi) != -1) {
                  newlist[m].canuse = true
                  newlist[m].other = PT_SKUIQuantity[canuselist.indexOf(newlist[m].zi)]
                  newlist[m].isselect = false
                } else {
                  newlist[m].canuse = false
                  newlist[m].isselect = false
                }
              }
              obj.yiji[y].xiaji = newlist
              obj.yiji[y].xiajiname = PT_SKUNV[x].ANName
              obj.yiji[y].isselect = false
            }
          }
          obj.yiji[0].isselect = true
          for (var x in obj.yiji[0].xiaji) {
            if (obj.yiji[0].xiaji[x].canuse) {
              obj.yiji[0].xiaji[x].isselect = true

              obj.morenselect = obj.yiji[0].xiaji[x].other
              break
            }
          }
        }
        console.log(canuselist)
        console.log(obj)
        this.setData({
          obj: obj
        })
      } else if (info.PT_SKUNV.length == 1) {
        var obj = {}
        obj.isdandu = e.currentTarget.dataset.isdandu==1?true:false
        obj.stylelength = 1
        obj.selfnum = 0

        var PT_SKUNV = info.PT_SKUNV

        var PT_SKUIQuantity = info.PT_SKUIQuantity

        var canuselist = []
        for (var x in PT_SKUIQuantity) {
          canuselist.push(PT_SKUIQuantity[x].ANVS)
        }

        console.log(canuselist)

        for (var x in PT_SKUNV) {
          var newlist = this.copyobj(PT_SKUNV[x].AVNameStr)

          for (var y in newlist) {
            newlist[y].zi = newlist[y].AVID + "_" + "0"
            if (canuselist.indexOf(newlist[y].zi) != -1) {
              newlist[y].canuse = true
            } else {
              newlist[y].canuse = false
            }
            newlist[y].isselect = false
            newlist[y].other = PT_SKUIQuantity[canuselist.indexOf(newlist[y].zi)]
          }
          for (var y in newlist) {
            if (newlist[y].canuse == true) {
              newlist[y].isselect = true

              obj.morenselect = newlist[y].other
              break
            }
          }

          // obj.yiji[0].isselect = true
          obj.yijiANName = PT_SKUNV[x].ANName
          obj.yiji = newlist

        }

        console.log(canuselist)
        console.log(obj)

        this.setData({
          obj: obj
        })

      }
      this.showsxselect()
    } else {
      // 无附加属性 

      var obj = {}
      obj.isdandu = e.currentTarget.dataset.isdandu == 1 ? true : false


      obj.stylelength = 0
      obj.selfnum = 0
      obj.othermsg=info

      this.setData({
        obj: obj
      })

      this.showsxselect()
    }

  },

  addcartbefor: function () {
    if(this.data.obj.selfnum==0){
      wx.showToast({
        title: '请添加商品数量',
        icon: 'none',
        duration: 2000
      })
    }else{
      var all = JSON.stringify(this.data.shopdetails[0])
      var obj = JSON.stringify(this.data.obj)
      wx.navigateTo({
        url: '/pages/sureorderpt/sureorderpt?all=' + all + '&obj=' + obj,
      })
    }
   
  },
  // addcart: function (SKUID = "", OrderNumber = 1) {
  //   var info = this.data.shopdetails[0]
  //   if (SKUID == "") {
  //     ajax('/api/ShopCart/AddCart?requestContent=' + JSON.stringify({
  //       token: wx.getStorageSync('Access_token'),
  //       ShopID: this.data.shopID,
  //       ProuductPublishID: info.ID,
  //       ProductID: info.ProductID,
  //       OrderNumber: OrderNumber,
  //       IMoney: info.PrevsufferingPrice,
  //       OriPrice: info.OriPrice,
  //     }), {
  //         header: {
  //           'Accept': 'application/x-www-form-urlencoded', // 默认值
  //         },
  //         method: "post",
  //       }, res => {
  //         // console.log(res)
  //         this.getcart()
  //         this.showsxselect()
  //       })
  //   } else {
  //     ajax('/api/ShopCart/AddCart?requestContent=' + JSON.stringify({
  //       token: wx.getStorageSync('Access_token'),

  //       ShopID: this.data.shopID,

  //       ProuductPublishID: info.ID,
  //       ProductID: info.ProductID,
  //       SKUID: SKUID,
  //       OrderNumber: OrderNumber,
  //       IMoney: this.data.obj.morenselect.PrevsufferingPrice,
  //       OriPrice: info.OriPrice,
  //     }), {
  //         header: {
  //           'Accept': 'application/x-www-form-urlencoded', // 默认值
  //         },
  //         method: "post",
  //       }, res => {
  //         console.log(res)
  //         console.log("1111111111111111")
  //         this.getcart()
  //         this.showsxselect()
  //       })


  //   }
  // },


  selectyiji: function (e) {
    var index = e.currentTarget.dataset.index
    var str = "obj.yiji[" + index + "].isselect"
    for (var x in this.data.obj.yiji) {
      var str1 = "obj.yiji[" + x + "].isselect"
      this.setData({
        [str1]: false
      })
    }
    this.setData({
      [str]: true
    })


    for (var x in this.data.obj.yiji) {
      for (var y in this.data.obj.yiji[x].xiaji) {
        var str11 = "obj.yiji[" + x + "].xiaji[" + y + "].isselect"
        this.setData({
          [str11]: false
        })
      }
    }

    for (var x in this.data.obj.yiji) {
      if (this.data.obj.yiji[x].isselect) {
        for (var aa in this.data.obj.yiji[x].xiaji) {
          if (this.data.obj.yiji[x].xiaji[aa].canuse == true) {
            var str12 = "obj.yiji[" + x + "].xiaji[" + aa + "].isselect"
            this.setData({
              [str12]: true
            })
            var str111 = "obj.morenselect"
            this.setData({
              [str111]: this.data.obj.yiji[x].xiaji[aa].other
            })
            break
          }
        }
      }
    }


  },

  selectyiji1: function (e) {
    var index = e.currentTarget.dataset.index
    var str = "obj.yiji[" + index + "].isselect"
    for (var x in this.data.obj.yiji) {
      var str1 = "obj.yiji[" + x + "].isselect"
      this.setData({
        [str1]: false
      })
    }
    this.setData({
      [str]: true
    })

    for (var y in this.data.obj.yiji) {
      if (this.data.obj.yiji[y].isselect == true) {
        var str1111 = "obj.morenselect"
        this.setData({
          [str1111]: this.data.obj.yiji[y].other
        })
        return
      }
    }

  },

  selecterji: function (e) {
    var index = e.currentTarget.dataset.index

    console.log(index)
    for (var x in this.data.obj.yiji) {
      for (var y in this.data.obj.yiji[x].xiaji) {
        var str11 = "obj.yiji[" + x + "].xiaji[" + y + "].isselect"
        this.setData({
          [str11]: false
        })
      }
    }
    for (var x in this.data.obj.yiji) {
      if (this.data.obj.yiji[x].isselect) {
        var str12 = "obj.yiji[" + x + "].xiaji[" + index + "].isselect"
        this.setData({
          [str12]: true
        })
        var str111 = "obj.morenselect"
        this.setData({
          [str111]: this.data.obj.yiji[x].xiaji[index].other
        })
      }
    }
  },


  //展示属性
  showsxselect: function () {
    this.setData({
      showsxselect: !this.data.showsxselect
    })

    if (this.data.showsxselect == false) {

    }
  },
  //去参团
  gocantuan:function(){
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  // 收藏
  shoucang:function(e){
    // console.log(e)
    let pgid = e.currentTarget.dataset.pgid;
    if (this.data.scstate == 0){
      ajax('/api/CollecIns/Insert?requestContent=' + JSON.stringify({
        token: wx.getStorageSync("Access_token"),
        PGID: pgid,
        VType: 1
      }), {
          header: {
            'Accept': 'application/x-www-form-urlencoded', // 默认值
          },
          method: "post",
        }, res => {
          console.log(res,'res')
          this.getdetails()
        })
    }else{
      ajax('/api/CollecDel/Del?requestContent=' + JSON.stringify({
        token: wx.getStorageSync("Access_token"),
        PGID: pgid,
        VType: 1
      }), {
          header: {
            'Accept': 'application/x-www-form-urlencoded', // 默认值
          },
          method: "post",
        }, res => {
          console.log(res, 'res')
          this.getdetails()
        })
    }
  },
  //剩余时间
  gettime:function(){
    for(var x in this.data.shopdetails){
      // console.log(this.data.shopdetails[x].EndDate.slice(3).split(':'))
      var arr = this.data.shopdetails[x].EndDate.split('天')[1].split(':');
      // console.log(this.data.shopdetails[x].EndDate.split('天'))
      this.setData({
        day: this.data.shopdetails[x].EndDate.split('天')[0],
        shi: arr[0],
        fen:arr[1],
        miao:arr[2]
      })
    }
  },
  //开团附加属性
  tuanshow:function(){
    this.setData({
      tuanshow:true
    })
  },
  // 隐藏属性框
  hiddentuan:function(){
    this.setData({
      tuanshow: false
    })
  },
  // 领劵框显示
  lingjuankuang:function(e){
    this.setData({
      juanshow:true
    })
    var ptid = e.currentTarget.dataset.ptid;
    this.setData({
      id: ptid
    })
    console.log(112)
    // console.log(ptid,'ptid')
    this.getjuan();
    
  },
  getjuan:function(){
    ajax('/api/CouponCollection/Get?requestContent=' + JSON.stringify({
      Vtype: 0,
      ActivityIDStr: this.data.id,
      PageIndex: 0,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      Title:"",
      token: wx.getStorageSync('Access_token')
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)
        this.setData({
          coupon: res.Models
        })
        for (var a in this.data.coupon) {
          this.setData({
            beginnyr: this.data.coupon[a].Bdate.slice(0, 10),
            endnyr: this.data.coupon[a].Edate.slice(0, 10)
          })
        }
      })
  },
  //分享领取
  tiaozhuan:function(){
    wx.navigateTo({
      url: '/pages/unpacking-securities/securities',
    })
  },
  // 立即领取
  lingjuan:function(e){
    let id=e.currentTarget.dataset.id
    // console.log(id,'id')
    ajax('/api/UploadReceiveCouponPrimaryNew/UploadAdd?requestContent=' + JSON.stringify({
      token: wx.getStorageSync("Access_token"),
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      UserCouponID: id
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res,'res')
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
        this.getjuan()
      })
  },
  // 隐藏领劵框
  hiddenkuang:function(){
    this.setData({
      juanshow:false
    })
  },
  getdetails:function(){
    ajax('/api/SpellBuyImmediately/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync("Access_token"),
      PTID: this.data.goodsID
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)
        this.setData({
          shopdetails: res.Models
        })
        for(var a in this.data.shopdetails){
          this.setData({
            scstate: this.data.shopdetails[a].SCState
          })
          console.log(this.data.shopdetails[a].PT_CGTZ.length)
        }
        this.gettime()
      })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })

    var ptid = options.ptid
    this.setData({
      goodsID: ptid
    })

    this.getdetails();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})